<template>
  <CommonPage show-footer title="字典数据">
    <template #action>
      <div>
        <n-button type="primary" class="ml-16" @click="handleAdd">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5"/>
          新建字典数据
        </n-button>
      </div>
    </template>

    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :extra-params="extraParams"
        :scroll-x="1200"
        :columns="columns"
        :get-data="api.dictDataPage"
        row-key="dictCode"
        @on-checked="onChecked"
        @on-data-change="(data) => (tableData = data)"
    >
      <template #queryBar>
        <QueryBarItem label="字典名称">
          <n-select
              v-model:value="queryItems.dictType"
              :options="state.dictTypeAllOptions"
              placeholder="请选择字典名称"
              label-field="dictName"
              value-field="dictType"
              children-field="children"
          />
        </QueryBarItem>
        <QueryBarItem label="字典标签">
          <n-input v-model:value="queryItems.dictLabel" placeholder="请选择字典标签"/>
        </QueryBarItem>
      </template>
    </CrudTable>
    <!-- 新增/编辑/查看 -->
    <CrudModal
        v-model:visible="modalVisible"
        :title="modalTitle"
        :loading="modalLoading"
        :show-footer="modalAction !== 'view'"
        @on-save="handleSave"
    >
      <n-form
          ref="modalFormRef"
          label-placement="left"
          label-align="left"
          :label-width="80"
          :model="modalForm"
          :disabled="modalAction === 'view'"
      >
        <n-form-item
            label="字典名称"
            path="dictName"
            :rule="{
            required: true,
            message: '请输入字典名称',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.dictName"/>
        </n-form-item>
        <n-form-item
            label="字典类型"
            path="dictData"
            :rule="{
            required: true,
            message: '请输入字典类型',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input-group>
            <n-input v-model:value="modalForm.dictData" placeholder="请输入字典类型"/>
            <n-popover trigger="hover">
              <template #trigger>
                <n-button type="primary" ghost>提示</n-button>
              </template>
              <span>数据存储中的Key值，如：sys_user_sex</span>
            </n-popover>
          </n-input-group>
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch v-model:value="modalForm.status" checked-value="0" unchecked-value="2">
            <template #checked>
              正常
            </template>
            <template #unchecked>
              停用
            </template>
          </n-switch>
        </n-form-item>
        <n-form-item
            label="备注"
            path="remark"
        >
          <n-input
              v-model:value="modalForm.remark"
              placeholder="请输入备注"
              type="textarea"
              :autosize="{
              minRows: 3,
              maxRows: 5,
            }"
          />
        </n-form-item>
      </n-form>
    </CrudModal>
  </CommonPage>
</template>

<script setup>
import {NButton, NSwitch} from 'naive-ui'
import {formatDateTime, renderIcon} from '@/utils'
import {useCRUD} from '@/composables'
import {useRoute} from 'vue-router'
import api from './api'

defineOptions({name: 'DictData'})

const route = useRoute()

const $table = ref(null)
/** 表格数据，触发搜索的时候会更新这个值 */
const tableData = ref([])
/** QueryBar筛选参数（可选） */
const queryItems = ref({
  dictType: ''
})
/** 补充参数（可选） */
const extraParams = ref({})
const state = reactive({
  dictTypeAllOptions: []
})

onMounted(() => {
  const {dictType} = route.query
  if (dictType) {
    queryItems.value.dictType = dictType
  }

  api.dictTypePage({
    page: 1,
    pageSize: 10000,
  }).then((res) => {
    state.dictTypeAllOptions = res.result.records
  })

  $table.value?.handleSearch()
})

const columns = [
  {type: 'selection', fixed: 'left'},
  {title: '编号', key: 'dictCode', width: 100, ellipsis: {tooltip: true}, resizable: true},
  {title: '字典标签', key: 'dictLabel', width: 130, ellipsis: {tooltip: true}, resizable: true},
  {
    title: '字典值', key: 'dictValue', width: 130, ellipsis: {tooltip: true}, resizable: true,
    render(row) {
      return h(NButton, {
        text: true,
        type: "success"
      }, {default: () => row['dictValue']});
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 150,
    resizable: true,
    render(row) {
      return h('span', formatDateTime(row['createTime']))
    },
  },
  {
    title: '最后更新时间',
    key: 'updateTime',
    width: 150,
    resizable: true,
    render(row) {
      return h('span', row['updateTime'] ? formatDateTime(row['updateTime']) : '')
    },
  },
  {
    title: '状态',
    key: 'status',
    width: 60,
    resizable: true,
    align: 'center',
    fixed: 'left',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row['status'],
        checkedValue: "0",
        uncheckedValue: "2",
        onUpdateValue: (value) => handlePublish({...row, status: value}),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 240,
    resizable: true,
    align: 'center',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              secondary: true,
              onClick: () => handleView(row.dictId),
            },
            {default: () => '查看', icon: renderIcon('majesticons:eye-line', {size: 14})}
        ),
        h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-left: 15px;',
              onClick: () => handleEdit(row.dictId),
            },
            {default: () => '编辑', icon: renderIcon('material-symbols:edit-outline', {size: 14})}
        ),

        h(
            NButton,
            {
              size: 'small',
              type: 'error',
              style: 'margin-left: 15px;',
              onClick: () => handleDelete(row.dictId),
            },
            {
              default: () => '删除',
              icon: renderIcon('material-symbols:delete-outline', {size: 14}),
            }
        ),
      ]
    },
  },
]

// 选中事件
function onChecked(rowKeys) {
  // if (rowKeys.length) $message.info(`选中${rowKeys.join(' ')}`)
}


const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleView,
  handleSave,
  handlePublish,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '字典',
  initForm: {dictSort: 1, status: '0'},
  doCreate: api.addDictType,
  doDelete: api.deleteDictType,
  doUpdate: api.updateDictType,
  doGetById: api.dictDataGetById,
  refresh: () => $table.value?.handleSearch(),
})
</script>
